<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use App\Models\ConfigGroup;
use App\Http\Controllers\AdminController;
use App\Models\Configuration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use DB;
use Artisan;

class SysController extends AdminController
{
    /**
     * 配置主页
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
		
        $groups = ConfigGroup::with(['configurations'=>function($q){return $q->orderBy('sort', 'asc');}])->where('model', 'config_sys')->orderBy('sort', 'asc')->get();
        return View::make('admin.sys.index', compact('groups'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function lists(Request $request)
    {
        return View::make('admin.sys.list');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $model = Configuration::query();
		
        if ($request->get('group_id')) {
            $model = $model->where('group_id', $request->get('group_id'));
        }
        if ($request->get('label')) {
            $model = $model->where('label', 'like', '%' . $request->get('label') . '%');
        }
        $res  = $model->orderBy('created_at', 'desc')->with(['cgroup'])->paginate($request->get('limit', 30))->toArray();
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit($id)
    {
        $configuration = Configuration::with('cgroup')->findOrFail($id);
        $groups        = ConfigGroup::get();
        return view('admin.sys.edit', compact('configuration', 'groups'));
    }

    /**
     * 添加配置
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        $groups = ConfigGroup::orderBy('sort', 'asc')->get();
        return View::make('admin.sys.create', compact('groups'));
    }

    /**
     * 添加配置
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $data = $request->all(['group_id', 'label', 'key', 'val', 'type', 'tips', 'sort']);
        $envData = $request->all(['key', 'val']);
        DB::beginTransaction();
        try {
            Configuration::create($data);
			$stt[$envData['key']]=$envData['val']; 
			sysEnv($stt);
		    Artisan::call('cache:clear');
			Artisan::call('config:clear');
            DB::commit();
            return Redirect::to(URL::route('admin.sys'))->with(['success' => '添加成功']);
        } catch (\Exception $exception) {
            return Redirect::back()->withErrors('添加失败');
        }
    }

    /**
     * 批量更新配置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $data = $request->except(['_token','_method','id']);
		$setData=[];
        DB::beginTransaction();
        try {
            foreach ($data as $k => $v) {
                DB::table('configuration')->where('key', $k)->update(['val' => $v]);
				$setData[$k]=$v;
            }
			  
			sysEnv($setData);
		    Artisan::call('cache:clear');
			Artisan::call('config:clear');
			
			DB::commit();
            return Response::json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();
            return Response::json(['code' => 1, 'msg' => '更新失败']);
        }
        return Response::json(['code' => 1, 'msg' => '更新失败']);
    }

    /**
     * 更新配置 单个更新
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateOne(Request $request, $id)
    {
        $data          = $request->only(['group_id', 'type', 'label', 'key', 'tips', 'sort']);
        $Configuration = Configuration::findOrFail($id);
        DB::beginTransaction();
        try {
            $Configuration->update($data);
            DB::commit();
            return Redirect::to(URL::route('admin.sys.list'))->with(['success' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();
            return Redirect::to(URL::route('admin.sys.list'))->with(['success' => '更新失败']);
        }
        return Redirect::to(URL::route('admin.sys.list'))->with(['success' => '更新失败']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        $Configuration = Configuration::whereIn('id', $ids)->get();
        if (!$Configuration) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        DB::beginTransaction();
        try {
            Configuration::destroy($ids);
            DB::commit();
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $exception) {
            DB::rollback();
            return response()->json(['code' => 1, 'msg' => '删除失败']);
        }
        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
